$(function () {
    var goods = new Goods();
});

var Goods = function () {
    this.init();
};
Goods.prototype = {
    $treeForm: $('#tree-form'), // 节点内容表单

    renderTreeFormEventKey: 'renderTreeForm', // 渲染节点内容表单事件
    $appendChildModal: $('#appendChildModal'),
    init: function () {
        var that = this;

        //刷新|加载 树数据
        $('.tree-reload').on('click', function () {
            that.queryTreeData(function (treData) {
                that.$treeForm.fadeOut("slow");
                that.initZTree(that.convertTreeDataToZTreeData(treData));
            });
        });
        $('.tree-reload').trigger('click');

        //表单渲染事件
        that.$treeForm.on(that.renderTreeFormEventKey, function () {
            var treeNode = that.$treeForm.data('treeNode');
            console.log(treeNode);
            that.$treeForm.find('input').each(function () {
                var $this = $(this);
                $this.val(treeNode.sourceData[$this.attr('name')]);
            });
            that.$treeForm.find('.delete')[treeNode.isParent ? 'addClass' : 'removeClass']('hide');
            that.$treeForm.fadeIn("slow");
        });

        // 表单验证
        that.$treeForm.validate({
            rules: {
                name: {
                    required: true,
                    minlength: 1,
                    maxlength: 20
                }
            },
            messages: {},
            errorPlacement: function (error, element) {
                error.insertAfter(element.parent());
            },
            //提交表单, 保存节点信息
            submitHandler: function () {
                that.saveRequest();
            }
        });

        // modal 隐藏时重置其内表单
        that.$appendChildModal.on('hidden.bs.modal', function (e) {
            that.$appendChildModal.find('form')[0].reset();
            $('[data-role=tagsinput]').tagsinput('removeAll');
        });

        //添加子节点 modal
        that.$appendChildModal.find('.append-child-btn').on('click', function () {
            if(that.$appendChildModal.find('[name=title]').val().length == 0) {
                layer.msg("请填写内容!", {icon: 7});
                return false;
            }
            var data = {
                parentId: Number(that.$treeForm.find('[name=id]').val()),
                name: that.$appendChildModal.find('[name=name]').val()
            }
            that.appendChildRequest(data);
        });

        // tag 输入加载
        $('[data-role=tagsinput]').tagsinput({
            trimValue: true,
            maxChars: 100
        });

        // 禁止表单自动提交, 而是通过 ajax
        $('form').submit(function () {
            return false;
        });

        //删除
        that.$treeForm.find('.btn.delete').on('click', function () {
            var id = that.$treeForm.find('[name=id]').val();
            that.deleteRequest(id);
        });

        return that;
    },
    //保存 ajax
    saveRequest: function () {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/classify/update',
            type: 'POST',
            dataType: 'json',
            data: that.$treeForm.serialize()
        }).done(function (data) {
            //表单中得input name, 对于树节点名称
            var name = that.$treeForm.find('[name=title]');
            //从树临时存储到form得节点信息
            var treeObj = $.fn.zTree.getZTreeObj("tree");
            //从表单中获得当前编辑的节点
            var treeNode = that.$treeForm.data('treeNode');
            //更新名称
            treeNode.name = name.val();
            //更新树
            treeObj.updateNode(treeNode);
            //提示框
            layer.msg(data.result);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('保存失败, 请稍后再试或联系开发人员 !', {icon: 2});
        })
    },
    //删除 ajax
    deleteRequest: function (id) {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/classify/' + id + '/delete',
            type: 'post',
            dataType: 'json'
        }).done(function (data) {
            //从树临时存储到form得节点信息
            var treeObj = $.fn.zTree.getZTreeObj("tree");
            //从表单中获得当前编辑的节点
            var treeNode = that.$treeForm.data('treeNode');
            // 从tree视图中移除节点
            treeObj.removeNode(treeNode);
            //提示框
            layer.msg(data.result);
            // 隐藏表单
            that.$treeForm.fadeOut("slow");
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('删除失败, 请稍后再试或联系开发人员 !', {icon: 2});
        })
    },
    //添加子节点 ajax
    appendChildRequest: function (data) {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/classify/appendChild',
            type: 'post',
            dataType: 'json',
            data: data
        }).done(function (data) {
            if(!data.success) {
                layer.msg(data.message, {icon: 7});
                return false;
            }
            var treeObj = $.fn.zTree.getZTreeObj("tree");
            //从表单中获得当前编辑的节点
            var treeNode = that.$treeForm.data('treeNode');
            // 讲已插入数据库的节点添加到tree视图中
            var newNodes = that.convertTreeDataToZTreeData(data.result['organizationList']);
            treeObj.addNodes(treeNode, newNodes);
            //隐藏modal
            that.$appendChildModal.modal('hide');
            //提示框
            layer.msg(data.message);
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('添加失败, 请稍后再试或联系开发人员 !', {icon: 2});
        })
    },
    //移动 ajax
    moveRequest: function (data) {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/classify/move',
            type: 'post',
            dataType: 'json',
            async: true,
            data: data,
        }).done(function (data) {
            layer.msg(data.message);
            // 隐藏表单
            that.$treeForm.fadeOut("slow");
        }).fail(function (jqXHR, textStatus, errorThrown) {
            layer.msg('移动失败, 请刷新页面节点!', {icon: 1})
        });
    },
    initZTree: function (zNodes) {
        var that = this;

        //"inner"：成为子节点，"prev"：成为同级前一个节点，"next"：成为同级后一个节点
        function beforeDrop(treeId, treeNodes, targetNode, moveType) {
            //不可移最外层区域
            if (!targetNode) {
                layer.msg('超出移动范围!', {icon: 7});
                return false;
            }
            //不可prev next 至根节点
            if ((moveType == 'next' || moveType == 'prev') && !targetNode.parentTId) {
                layer.msg('不可移动至根节点前后!', {icon: 7});
                return false;
            }
            //if(!hasUpdateNodePermission) {
            //    layer.msg('抱歉, 您没有移动更新的权限, 如需要, 请联系系统管理员 !', {icon: 7});
            //    return false;
            //}
            //仅为支付排序使用, 不支持移动至气态parent节点.
            //if (treeNodes[0].parentTId != targetNode.parentTId) {
            //    layer.msg('仅支持同级节点排序!', {icon: 7});
            //    return false;
            //}
            //ajax 移动节点
            var data = {sourceId: treeNodes[0].id, targetId: targetNode.id, moveType: moveType};
            that.moveRequest(data);

            return true;
        }

        function zTreeOnClick(event, treeId, treeNode) {
            that.$treeForm.data('treeNode', treeNode);
            that.$treeForm.trigger(that.renderTreeFormEventKey);
        };
        function zTreeBeforeDrag(treeId, treeNodes) {
            that.$treeForm.fadeOut("slow");
        };

        var setting = {
            data: {
                simpleData: {
                    enable: true
                }
            },
            view: {
                selectedMulti: false
            },
            edit: {
                enable: true,
                editNameSelectAll: false,
                drag: {
                    //因为目前不支持排序的操作
                    prev: true,
                    next: true,
                    inner: true
                },
                showRemoveBtn: false,
                showRenameBtn: false
            },
            callback: {
                //如果返回 false，zTree 将恢复被拖拽的节点，也无法触发 onDrop 事件回调函数
                beforeDrop: beforeDrop,
                onClick: zTreeOnClick,
                beforeDrag: zTreeBeforeDrag
            }
        };
        $.fn.zTree.init($("#tree"), setting, zNodes);
    },
    queryTreeData: function (callback) {
        var that = this;
        $.ajax({
            url: window['ctx'] + '/classify/tree/data',
            type: 'get',
            dataType: 'json',
            cache: false,
            success: function (response) {
                callback && callback(response.result);
            },
            error: function (res) {
                layer.alert(res)
            }
        });
        return that;
    },
    //讲存储的数据转换为zTree标准格式.
    convertTreeDataToZTreeData: function (treeData) {
        var zTreeData = [];
        $.each(treeData, function (idx, item) {
            zTreeData.push({id: item.id, pId: item.parentId, name: item.title, open: false, sourceData: item})
        });
        return zTreeData;
    }
};